package org.wotou.authority.utils;

import com.fasterxml.jackson.annotation.JsonIgnore;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.util.StringUtils;

/**
 * 分页工具类
 *
 * @author zhangQ
 * @date 2017/12/8
 */
public final class PageUtil<T> {
    /**
     * pageJpa 生成PageRequest,
     *
     * @return
     */
    @JsonIgnore
    public static Pageable getPageable(PageJpa pageJpa) {
        PageRequest pageable = null;
        if (StringUtils.isEmpty(pageJpa.getSortName()) == false) {
            pageable = new PageRequest(pageJpa.getPageNumber() - 1,
                    pageJpa.getPageSize(),
                    "desc".equals(pageJpa.getSortOrder()) ? Sort.Direction.DESC : Sort.Direction.ASC, pageJpa.getSortName());
        } else {
            pageable = new PageRequest(pageJpa.getPageNumber() - 1,
                    pageJpa.getPageSize());
        }
        return pageable;
    }

    /**
     * 根据返回的page类生成PageJpa
     *
     * @param pageResult
     * @param <E>
     * @return
     */
    @JsonIgnore
    public static <E> PageJpa<E> getData(Page<E> pageResult) {
        PageJpa<E> page = new PageJpa<E>();
        Page<E> p = pageResult;
        if (p != null) {
            page.setTotal(p.getTotalElements());
            page.setRows(p.getContent());
        }
        return page;
    }
}
